//
//  PeopleInfoDetailView.swift
//  newxyt
//
//  Created by 谭钧豪 on 16/2/5.
//  Copyright © 2016年 谭钧豪. All rights reserved.
//

import UIKit

class CellMenuItem: UIMenuItem{
    var indexPath: NSIndexPath!
}

class PeopleInfoDetailView: UITableViewController {

    var people = Friend()
    var intend:UIBarButtonSystemItem!
    var friendInfo = [String:AnyObject]()
    let ip = NSUserDefaults.standardUserDefaults().valueForKey("ip") as! String
    let userid = NSUserDefaults.standardUserDefaults().valueForKey("username")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        var rightbaraction = "Add"
        if intend == UIBarButtonSystemItem.Trash{
            rightbaraction = "Delete"
        }else if intend == UIBarButtonSystemItem.Done{
            rightbaraction = "Done"
            people.userid = userid as! String
        }
        let item = UIBarButtonItem(barButtonSystemItem: intend, target: self, action: Selector(rightbaraction))
        self.navigationItem.rightBarButtonItem = item
        let FriendInfo = data()
        for attr in people.allattr{
            friendInfo[attr] = FriendInfo.objectForKey(attr)
        }
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return friendInfo.count
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row != 0{
            return 40
        }else{
            return 80
        }
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.row != 0{
            let cell = tableView.dequeueReusableCellWithIdentifier("friendInfoCell", forIndexPath: indexPath) as! FriendInfoCell
            let attr = people.allattr[indexPath.row]
            cell.attrLabel.text = people.attrname[attr]
            if people.userid != userid as! String{
                let longtap = UILongPressGestureRecognizer(target: self, action: Selector("display:"))
                longtap.minimumPressDuration = 0.5
                cell.valueLabel.addGestureRecognizer(longtap)
                cell.valueLabel.userInteractionEnabled = true
                if let friendInfoAttr = friendInfo[attr]{
                    cell.valueLabel.text = String(friendInfoAttr)
                }else{
                    cell.valueLabel.text = ""
                }
            }else{
                let tfframe = CGRectMake(cell.valueLabel.frame.origin.x, cell.valueLabel.frame.origin.y-5, self.view.frame.width/3*2, cell.valueLabel.frame.height+10)
                let valuetf = UITextField(frame: tfframe)
                if let friendInfoAttr = friendInfo[attr]{
                    valuetf.text = String(friendInfoAttr)
                }else{
                    valuetf.text = ""
                }
                valuetf.layer.borderColor = UIColor.grayColor().CGColor
                valuetf.layer.borderWidth = 1
                valuetf.layer.cornerRadius = 5
                cell.addSubview(valuetf)
                cell.valueLabel.removeFromSuperview()
            }
            return cell
        }else{
            let cell = UITableViewCell()
            cell.textLabel?.text = "我是头像"
            cell.textLabel?.textAlignment = .Center
            return cell
        }
        
    }
    
    
    func Add(){
        let friendid = String(friendInfo["userid"]!)
        let action = "addFriend?data="
        var url = "{\"petitor\":\"\(userid!)\",\"receiver\":\"\(friendid)\"}"
        url = ip + action + url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
        let warning = UIAlertController(title: "提示", message: "将向对方发送好友邀请", preferredStyle: .Alert)
        let okAction = UIAlertAction(title: "确定", style: .Cancel, handler: {
            (UIAlertAction) ->Void in
            self.request(url)
            
        })
        let cancelAction = UIAlertAction(title: "取消", style: .Default, handler: nil)
        warning.addAction(okAction)
        warning.addAction(cancelAction)
        presentViewController(warning, animated: true, completion: nil)
    }
    
    func Delete(){
        let friendid = String(friendInfo["userid"]!)
        let action = "deletefriend?data="
        var url = "{\"username\":\"\(userid!)\",\"friend\":\"\(friendid)\"}"
        url = ip + action + url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
        let warning = UIAlertController(title: "警告", message: "确认删除你的好友吗？", preferredStyle: .Alert)
        let okAction = UIAlertAction(title: "确定", style: .Cancel, handler: {
            (UIAlertAction) ->Void in
            self.request(url)
        })
        let cancelAction = UIAlertAction(title: "取消", style: .Default, handler: nil)
        warning.addAction(okAction)
        warning.addAction(cancelAction)
        presentViewController(warning, animated: true, completion: nil)
    }
    
    func Done(){
        print("进入资料修改提交")
    }
    
    func request(url:String){
        var statu = 1
        print(url)
        let request = NSURLRequest(URL:NSURL(string:url)!,cachePolicy:NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData,timeoutInterval:2.0)
        let session = NSURLSession.sharedSession()
        let semaphore = dispatch_semaphore_create(0)
        let dataTask = session.dataTaskWithRequest(request, completionHandler: {
            (data, response, error) -> Void in
            if error != nil{
                print("获取出错")
                print(error)
            }else{
                do{
                    let statustr = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSNumber
                    statu = statustr.integerValue
                    
                }catch{print("解析出错")}
            }
            dispatch_semaphore_signal(semaphore)
            
        }) as NSURLSessionTask
        dataTask.resume()//启动线程
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)//等待线程结束
        let tip = UIAlertController(title: "提示", message: "", preferredStyle: .Alert)
        let OKAction = UIAlertAction(title: "好", style: .Default, handler: nil)
        tip.addAction(OKAction)
        if statu == 0 {
            tip.message = "发送好友申请成功"
        }else if statu == 3{
            tip.message = "你曾经发送过邀请，请等候对方接受"
        }else{
            tip.message = "发送好友申请失败，请联系管理员"
        }
        presentViewController(tip, animated: true, completion: nil)
    }
    
    func data() -> AnyObject {
        
        
        let action = "profile?data="
        let username = people.userid
        var datas:AnyObject?
        var url = "{\"username\":\"\(username)\"}"
        
        url = ip + action + url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())!
        let request = NSURLRequest(URL:NSURL(string:url)!,cachePolicy:NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData,timeoutInterval:10.0)
        let session = NSURLSession.sharedSession()
        let semaphore = dispatch_semaphore_create(0)
        let dataTask = session.dataTaskWithRequest(request, completionHandler: {
            (data, response, error) -> Void in
            if error != nil{print("获取出错")
            }else{
                do{
                    datas = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
                    
                    
                }catch{print("解析出错")}
            }
            dispatch_semaphore_signal(semaphore)
            
        }) as NSURLSessionTask
        
        dataTask.resume()//启动线程
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)//等待线程结束
        return datas!
    }
    
    override func canBecomeFirstResponder() -> Bool {
        return true
    }
    
    override func canResignFirstResponder() -> Bool {
        return true
    }
    

    
    
    func copyLine(menuController: UIMenuController) {
        let menuItem: CellMenuItem = UIMenuController.sharedMenuController().menuItems![0] as! CellMenuItem
        if menuItem.indexPath != nil {
            let value = String(friendInfo[people.allattr[menuItem.indexPath.row]]!)
            let pasteboard = UIPasteboard.generalPasteboard()
            pasteboard.string = value
        }
    }
    
    //end menu delegate
    
    //action handler of longPressGesture
    func display(gesture: UILongPressGestureRecognizer)
    {
        if gesture.state == UIGestureRecognizerState.Began{
            gesture.view?.becomeFirstResponder()
            let pressedIndexPath = self.tableView.indexPathForRowAtPoint(gesture.locationInView(self.tableView))
            let menu = UIMenuController.sharedMenuController()
            let copyItem = CellMenuItem(title: "复制", action: Selector("copyLine:"))
            copyItem.indexPath = pressedIndexPath
            menu.menuItems = [copyItem]
            var cellRect = self.tableView.rectForRowAtIndexPath(pressedIndexPath!)
            cellRect.origin.x = cellRect.origin.x - 10.0
            cellRect.origin.y = cellRect.origin.y + 20.0
            menu.setTargetRect(cellRect, inView: self.tableView)
            menu.setMenuVisible(true, animated: true)
        }
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
